package com.boot.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
@Slf4j
public class LocalFileStorageService {
    @Value("${file.upload.dir}")
    private String uploadDir;

    public String uploadFile(MultipartFile file) throws IOException {
        //生成唯一名字
        String fileName = file.getOriginalFilename();
        String fileExt = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = UUID.randomUUID() + fileExt;
        //储存文件
        String filePath = uploadDir + newFileName;
        file.transferTo(new File(filePath));
        return newFileName;
    }

    public boolean deleteFile(String fileName) {
        File file = new File(uploadDir + fileName);
        if (file.exists()) {
            boolean delete = file.delete();
            if (delete) log.info("删除文件成功");
            return delete;
        }
        return true;
    }
}
